package com.collectplus.express.self;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import com.collectplus.express.BaseActivity2;
import com.collectplus.express.R;
import com.collectplus.express.logic.AppCache;
import com.collectplus.express.logic.AppHttp;
import com.collectplus.express.logic.AppLogic;
import com.collectplus.express.logic.AppResult;
import com.collectplus.express.logic.DialogMgr;
import com.collectplus.express.logic.JSON;
import com.collectplus.express.logic.MsgID;
import com.collectplus.express.model.Const;
import com.collectplus.express.model.OrderBean;
import com.collectplus.express.model.ReceiverBean;
import com.collectplus.express.model.SenderBean;
import com.collectplus.express.model.ServicePointBean;
import com.collectplus.express.order.OrderPayActivity;
import com.shouhuobao.bhi.login.LoginActivity;

import droid.frame.umeng.UMeng;
import droid.frame.utils.android.MathUtils;

/**
 * 自助寄件、订单确认界面
 *
 * @author coffee <br>
 * 2016-9-26下午2:07:25
 */
public class SelfOrderSubmitActivity extends BaseActivity2 implements OnClickListener {

    private ReceiverBean cacheReceiver;
    private RadioGroup mRadioGroup;

    @Override
    @SuppressLint("ResourceAsColor")
    protected void onCreate(Bundle savedInstanceState) {
        cacheReceiver = AppCache.getParcelNew();
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void findViewById() {
        setContentView(R.layout.self_order_submit);
        super.findViewById();
        getAppTitle().setCommonTitle("确认订单");
        // 投递袋编码
        TextView bagCode = (TextView) findViewById(R.id.self_order_bagcode);
        if (cacheReceiver.getBag() != null) {
            if (isNotEmpty(cacheReceiver.getBag().getCode())) {
                bagCode.setText(cacheReceiver.getBag().getCode());
            } else {
                bagCode.setText(getString(R.string.parcel_nobag_code));
            }
        } else {
            bagCode.setText(getString(R.string.parcel_nobag_code));
        }
        // 投递点地址
        TextView serviceAddress = (TextView) findViewById(R.id.self_order_address);
        //投递方式标题，上门位置或投递点
        TextView serviceSendType = (TextView) findViewById(R.id.self_order_type_tv);
        //投递方式
        TextView serviceType = (TextView) findViewById(R.id.send_type_tv);
        //返回重新修改
        TextView backModifiersTV = (TextView) findViewById(R.id.back_modifiers_tv);
        //上门取件方式
        if (cacheReceiver.getType() == Const.ParcelType.visitToHome) {
            serviceType.setText("火箭侠上门取件");
            serviceSendType.setText("上门位置：");
            serviceAddress.setText(cacheReceiver.getVisitDoorBean().getAddress() + cacheReceiver.getVisitDoorBean().getAddressDesc());
            //是否显示返回修改
            backModifiersTV.setVisibility(View.VISIBLE);
            backModifiersTV.setOnClickListener(this);
        } else {
            serviceType.setText("驿站投递");
            serviceSendType.setText("投递点：");
            serviceAddress.setText(cacheReceiver.getServicePoint().getAddress());
            backModifiersTV.setVisibility(View.GONE);
            backModifiersTV.setOnClickListener(null);
        }
        // 收件人信息
        String addr = cacheReceiver.getProvince() + "" + cacheReceiver.getCity() + "" + cacheReceiver.getDistrict() + "" + cacheReceiver.getAddress();
        TextView receiverAddress = (TextView) findViewById(R.id.receiver_address);
        receiverAddress.setText(addr);
        // 收件人姓名
        TextView receiverName = (TextView) findViewById(R.id.receiver_name);
        receiverName.setText(cacheReceiver.getName());
        // 收件人电话
        TextView receiverPhone = (TextView) findViewById(R.id.receiver_phone);
        receiverPhone.setText(cacheReceiver.getPhone());
        // set onclick event
        findViewById(R.id.self_form_submit).setOnClickListener(this);

        // 处理寄件人信息
        SenderBean sender = cacheReceiver.getSender();
        TextView senderName = (TextView) findViewById(R.id.sender_name);
        TextView senderPhone = (TextView) findViewById(R.id.sender_phone);
        TextView senderAddr = (TextView) findViewById(R.id.sender_address);
        if (sender == null) {
            ((ViewGroup) senderName.getParent()).setVisibility(View.GONE);
            senderPhone.setVisibility(View.GONE);
            ((ViewGroup) senderAddr.getParent()).setVisibility(View.GONE);
        } else {
            senderName.setText(sender.getName());
            senderPhone.setText(sender.getPhone());
            // 如果详细地址(包括省市区)不为空,
            if (isNotEmpty(sender.getAddressDetails())) {
                // 省市区不为空
                if (isNotEmpty(sender.getProvince())) {
                    senderAddr.setText(sender.getProvince() + sender.getCity() + sender.getDistrict());
                    senderAddr.append(sender.getAddress());
                } else {
                    senderAddr.setText(sender.getAddress());
                }
            } else {
                ((ViewGroup) senderAddr.getParent()).setVisibility(View.GONE);
            }
        }
        //
        TextView remark = (TextView) findViewById(R.id.self_remark);
        if (isNotEmpty(cacheReceiver.getRemark())) {
            remark.setText(cacheReceiver.getRemark());
        } else {
            remark.setVisibility(View.GONE);
        }
        mRadioGroup = (RadioGroup) findViewById(R.id.pay_group);
        RadioButton radioButton1 = (RadioButton) findViewById(R.id.radio_1);
        RadioButton radioButton2 = (RadioButton) findViewById(R.id.radio_2);
        final ServicePointBean pointBean = cacheReceiver.getServicePoint();
        // 线上支付
        if (pointBean.getPayType() == 1) {
            radioButton1.setChecked(true);
            radioButton2.setEnabled(false);
            pointBean.setSubmitPayType(1);
            // 到店支付
        } else if (pointBean.getPayType() == 2 || pointBean.getPayType() == 0) {
            radioButton2.setChecked(true);
            radioButton1.setEnabled(false);
            pointBean.setSubmitPayType(0);
        } else {
            radioButton1.setChecked(true);
            pointBean.setSubmitPayType(1);
        }
        //寄件物品信息
        ((TextView) findViewById(R.id.goods_info_tv)).setText(pointBean.getGoodsType() + cacheReceiver.getWeight() + "kg");
        // setPayMoney(pointBean);

        mRadioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.radio_1) {
                    pointBean.setPayType(1);
                    pointBean.setSubmitPayType(1);
                } else {
                    pointBean.setPayType(2);
                    pointBean.setSubmitPayType(0);
                }
                // setPayMoney(pointBean);
            }
        });
    }

    /**
     * 设置支付金额
     *
     * @param pointBean
     */
    private void setPayMoney(ServicePointBean pointBean) {
        // 待支付价格
        TextView mMoneyTv = (TextView) findViewById(R.id.pay_money_tv);
        TextView isCash = (TextView) findViewById(R.id.order_cash);
        if (pointBean.getPayType() == 2) {
            isCash.setText("到店支付");
            mMoneyTv.setVisibility(View.INVISIBLE);
        } else {
            mMoneyTv.setVisibility(View.VISIBLE);
            String payMomeyTv = String.format("￥%s", this.money(cacheReceiver.getBag().getPrice(), ""));
            int end = payMomeyTv.indexOf(".");
            int start = payMomeyTv.indexOf('￥') + 1;
            SpannableString msp = new SpannableString(payMomeyTv);// 实际支付：
            // 设置字体大小（相对值,单位：像素） 参数表示为默认字体大小的int多少倍
            msp.setSpan(new RelativeSizeSpan(2.0f), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            mMoneyTv.setText(msp);
        }
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {
            case MsgID.order_upload_image:
                AppResult<String> result1 = JSON.parser(msg.obj, String.class);
                if (result1.isSuccess()) {
                    showLoadingDialog("提交订单");
                    cacheReceiver.setParcelImgUrl(result1.getResult());
                    ServicePointBean servicePoint = cacheReceiver.getServicePoint();
                    if (Const.ParcelType.visitToHome == servicePoint.getType()) {
                        AppHttp.getInstance().bagToHome(null, null);
                    } else if (Const.ParcelType.bagToHome == servicePoint.getType()) {//驿站
                        AppHttp.getInstance().orderWithBag(null, null);
                    } else {//到柜
                        AppHttp.getInstance().orderWithBox(null, null);
                    }
                } else {
                    showToast(result1.getMessage());
                }
                return true;
            // 下单
            case MsgID.order_new:
                cancelLoadingDialog();
                final AppResult<OrderBean> result = JSON.parser(msg.obj, OrderBean.class);
                if (result.isSuccess()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            ServicePointBean pointBean = cacheReceiver.getServicePoint();
                            OrderBean order = result.getResult();
                            if (order.isValid()) {
                                if (pointBean.getPayType() == 1 || (pointBean.getPayType() == 3 && mRadioGroup.getCheckedRadioButtonId() == R.id.radio_1)) {
                                    UMeng.click(getContext(), "select_submit_order_click");
                                    Intent intent = new Intent();
                                    OrderBean orderBean = result.getResult();
                                    intent.putExtra("item", result.getResult());
                                    intent.putExtra("from", SelfOrderSubmitActivity.class.getName());
                                    intent.putExtra("orderId", orderBean.getOrderId());
                                    intent.setClass(getContext(), OrderPayActivity.class);
                                    startActivity(intent);
                                } else {
                                    AppCache.setOrder(order);
                                    AppLogic.getInstance().onPaySuccess(getContext());
                                }
                            } else {
//                                DialogMgr.showSubmitOrderTipsDialog(getContext());
                                DialogMgr.notNearByCourierTips(getContext());
                            }
                        }
                    });
                } else {
                    showToast(result.getMessage());
                }
                return true;
            default:
                return super.handleMessage(msg);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            // 下单
            case R.id.self_form_submit:
                if (isLogin() == false) {
                    startActivity(LoginActivity.class);
                    return;
                }
                ServicePointBean pointBean = cacheReceiver.getServicePoint();
                // 线上支付
                if (null == pointBean.getPayType() || pointBean.getPayType() == 1) {
                    UMeng.click(getContext(), "self_order_submit_online_click");
                    // 到店支付
                } else if (pointBean.getPayType() == 2 || pointBean.getPayType() == 0) {
                    UMeng.click(getContext(), "self_order_submit_reachshop_click");
                } else {
                    UMeng.click(getContext(), "self_order_submit_online_click");
                }
                UMeng.click(getContext(), "self_order_submit_click");
                showLoadingDialog("上传包裹图片");
                AppHttp.getInstance().orderImageUpdate(cacheReceiver.getImageUrl());
                break;
            //返回进行修改
            case R.id.back_modifiers_tv:
                finish();
                break;
            default:
                break;
        }

    }

    /**
     * 实际支付结果
     *
     * @param bagMoney       投递袋结果
     * @param favorableMoney 邮票价格
     * @return 实际支付结果
     */
    private double money(String bagMoney, String favorableMoney) {
        double mMoney = MathUtils.sub(bagMoney, favorableMoney);
        if (mMoney <= 0) {
            return 0.01;
        }
        return mMoney;
    }
}
